package com.crazy.common.page;

import java.io.Serializable;
import java.util.List;

import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

/**
 * 分页类：主要提供上页页号、当前页号、下页页号、每页数量、总页数、总记录数、是否首页、是否末页、数据集合
 * 
 * @author Zhang Weiwei
 * @since 2013-10-1上午11:38:43
 */
@SuppressWarnings("serial")
public class Pager<Entity> extends PageImpl<Entity> implements Serializable {
	public static final int DEFAULT_COUNT = 10;
	private List<Entity> content;
	private int pageNum = 1;
	private int pageSize = DEFAULT_COUNT;
	private int totalCount = 0;

	public Pager(List<Entity> content) {
		super(content);
	}

	public Pager(List<Entity> content, Pageable pageable, Number total) {
		super(content, pageable, total.longValue());
		this.content = content;
		this.setPageNum(pageable.getPageNumber());
		this.setPageSize(pageable.getPageSize());
		this.setTotalCount(total.intValue());
	}

	/**
	 * 下页页号
	 */
	public int getNextPage() {
		return this.isLast() ? this.pageNum : this.pageNum + 1;
	}

	/**
	 * 上页页号
	 */
	public int getPrePage() {
		return this.isFirst() ? this.pageNum : this.pageNum - 1;
	}

	/**
	 * 获得分页内容
	 */
	@Override
	public List<Entity> getContent() {
		return this.content;
	}

	/**
	 * 当前页号
	 */
	@Override
	public int getNumber() {
		return this.pageNum;
	}

	/**
	 * 总记录数
	 */
	@Override
	public long getTotalElements() {
		return this.totalCount;
	}

	/**
	 * 总页数
	 */
	@Override
	public int getTotalPages() {
		int totalPage = this.totalCount / this.pageSize;
		return (totalPage == 0 || this.totalCount % this.pageSize != 0) ? ++totalPage
				: totalPage;
	}

	/**
	 * 是否第一页
	 */
	@Override
	public boolean isFirst() {
		return this.pageNum <= 1;
	}

	/**
	 * 是否最后一页
	 */
	@Override
	public boolean isLast() {
		return this.pageNum >= this.getTotalPages();
	}

	@Override
	public boolean hasPrevious() {
		return !this.isFirst();
	}

	public void setContent(List<Entity> content) {
		this.content = content;
	}

	public void setPageNum(Integer pageNum) {
		this.pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = (pageSize == null || pageSize < 1) ? DEFAULT_COUNT
				: pageSize;
	}

	public void setTotalCount(Integer totalCount) {
		this.totalCount = (totalCount == null || totalCount < 0) ? 0
				: totalCount;
	}
}
